﻿/// <reference path="../Plugs/Parts/widgets.js" />
/// <reference path="../Plugs/xbox/xbox.js" />
/// <reference path="jquery.extention.js"/>
window.$lv = new
function $lv() {
    this.fmjid = "#";
    this.resolveUrl = function (r) {
        return $siteurl + r.replace("~/", "");
    };

    this.burl = function (search, baseUrl) {
        /// <summary>组建URL，baseUrl默认为window.location，search不需要&前缀</summary>
        var a = document.createElement("a");
        a.href = baseUrl ? baseUrl : window.location;
        var url = a.toString(); var len = url.length;

        if (a.hash) { a.href = url.substr(0, len - a.hash.length); }
        else if (url[len - 1] == '#') { a.href = url.substr(0, len - 1); }

        a.search += (a.search ? "&" : "") + search;
        return a.toString();
    };

    this.serialize = function (select, append) {
        jQuery(select).serialize() + "&" + append;
    };
    this.toast = function toast(message) {
        /// <summary>显示提示信息，如: $df.toast("Hello world!");</summary>
        //$(document).message(message);
        layer.msg(message);       
        
    };
    this.confirm = function (msg, ensure, cancel, onshow) {
        var msghtml = '<div style="padding:8px 10px;">' + msg + '</div>';
        dialog.showMsgbox(msgboxType.confirm, msghtml, null, ensure, cancel, onshow);
    }


    function ajaxError(xhr, textStatus, errorThrown) {
        /// <summary>处理jquery.ajax时的异常</summary>
        window.$lv.toast(textStatus + "," + errorThrown);
    }
    /// <summary>返回html内容</summary>
    /// <param name="container" type="string or obj">返回内容容器(jq选择器或jq obj)</param>
    /// <param name="replace" type="bool">replace掉容器</param>
    this.actionHtml = function (url, container,data, callback, replaceContainer) {
        var m = this;
        var idx = layer.load(2);
        if (!data) { data = $(this.fmjid).serialize(); }
        this.post(url, data, function (r) {
            layer.close(idx);
            if (r) {
                replaceContainer && $(container).replaceWith(r) || $(container).html(r);
            }
            typeof callback == 'function' && callback(r);
        }, "html");
    }

    this.actionJson = function (url, callback, formId, data) {
        var idx = layer.load(2);
        if (!data) {//不传data，取form数据
            var form = formId ? this.fmjid + formId : this.fmjid;
            data = jQuery(form).serializeObject();
            data = JSON.stringify(data);
        }
        var m = this;
        this.post(url, data, function (r) {
            layer.close(idx);
            typeof callback == 'function' && callback(r);
        }, "json");
    }

    this.actionSync = function (action, callback, data) {
        /// <summary>向当前页面发送action请求</summary>
        var url = this.burl("action=" + action);
        if (!data) { data = jQuery(this.fmjid).serialize(); }
        this.postSync(url, data, callback);
    };

    // ajax post data
    this.post = function (url, data, callback, dataType) {
        /// <summary>提交数据，如：$df.post("edit.aspx", {id:1,name:'abcd'}, function(r){alert(r);})</summary>
        jQuery.ajax({ type: 'POST', url: url, contentType: "application/json; charset=utf-8", data: data, success: callback, dataType: dataType, timeout: 30 * 1000, error: ajaxError });
    };
    this.postSync = function (url, data, callback) {
        /// <summary>提交数据，如：$df.post("edit.aspx", {id:1,name:'abcd'}, function(r){alert(r);})</summary>
        jQuery.ajax({ type: 'POST', async: false, url: url, data: data, success: callback, dataType: "html", timeout: 30 * 1000, error: ajaxError });
    };
    this.get = function (url, data, callback, dataType) {
        /// <summary>提交数据，如：$df.post("edit.aspx", {id:1,name:'abcd'}, function(r){alert(r);})</summary>
        jQuery.ajax({ type: 'get', url: url, data: data, success: callback, dataType: dataType, timeout: 30 * 1000, error: ajaxError });
    };

    /// <summary>Ajax时是否自动开启BlockUI</summary>
    this.blockAjaxUI = true;
    this.noBlocAjaxkUI = function () {
        /// <summary>Ajax时不开启BlockUI</summary>
        this.blockAjaxUI = false;
    };
    this.blocAjaxkUI = function () {
        /// <summary>Ajax时启动BlockUI</summary>
        this.blockAjaxUI = true;
    };

    this.blockUI = function blockUI(message, timeout) {
        /// <summary>显示遮罩层，如： $df.blockUI(); </summary>
        if (!message) message = "正在处理...";
        message = '<h1 style="white-space:nowrap; padding:15px;margin:0">' + message + '</h1>'
        var options = {}; options.message = message; if (timeout) options.timeout = timeout;
        try { $.blockUI(options); } catch (er) { }
    };

    this.unblockUI = function unblockUI() {
        /// <summary>关闭遮罩层</summary>
        try { $.unblockUI(); } catch (er) { }
    };

    this.table = function (selector, reload) {
        /// <summary>初始化表格，注册排序、分页事件</summary>
        jQuery(selector).tableInit(reload);
    };

};


var noticeType = { Talk: 1, Msg: 2, Git: 3, AskFriend: 4 };

var $hlp = {
    lid: $utl.getCookie($uiCookie),
    loginBox: function () {
        this.downloadVchkJs();
        dialog.showLitebox('.modal-login', function (r) {
            if (r) {//登录成功
                //window.location.href = '/' + r;
                //window.location.hash = '#lg';
                window.location.reload()
            }
        })
    },
    checkLogin: function (notShowLoginBox) {
        var canAccess = access.getAccess(accessLevel.login);

        canAccess || notShowLoginBox || this.loginBox();

        return canAccess;
    }, gitStart: function (toId, toNick) {
        if (!this.checkLogin()) return;

        if ($('.gguid').length == 0) {//页面添加向导内容
            $('<div/>').attr('class', 'gguid').append('<ul class="mre"><i class="fa fa-close" onclick="dialog.closeLiteBox(\'.gguid\');"></i><li type="v"><i class="fa fa-gift"></i>虚拟礼物</li><li type=""><i class="fa fa-gift"></i>实体礼物</li></ul>').appendTo('body');
            //实体btn click
            $('.mre li').click(function () {
                var real = $(this).attr('type') == 'v' ? false : true;
                showGit(real, toId, toNick);
                //dialog.closeLiteBox('.gguid');
            });
        }
        dialog.showLitebox('.gguid');

        function showGit(real, toId, toNick) {
            var box = real ? '#gitbox' : '#gitboxv';
            if ($(box).length > 0) {
                dialog.showLitebox(box);
                return;
            }
            $lv.get('/gift/gitbox' + (real ? '' : 'v'), null, function (r) {
                //alert(r);
                $('body').append(r);
                //调用gitbox函数
                onshowGit(toId, toNick);

                dialog.showLitebox(box);
            }, 'html');
        }
    }, msgStart: function (toId, toNick) {
        if (!this.checkLogin()) return;
        dialog.showBox('a-edit', 'id:func', '发送私信', null, 480, 260, function ($c) {
            //获取msgbox显示
            $lv.actionHtml('/Msg/Sendbox?nick=' + escape(toNick), $c, {}, function (r) {
                if (!r) return;
                var $tmt = $c.find('.tmt'), $tarea = $c.find('.tarea');
                $c.find('.i-close').click(function () {
                    $tmt.hide();
                    $tarea.focus();
                });
                $tarea.focus(function () {
                    $tmt.hide();
                }).blur(function () {
                    $tmt.show();
                });
                $c.find('.btn-save').click(function () {

                    var con = $c.find('textarea[name="Content"]').val().trim();
                    if (con.length == 0) { $lv.toast('请输入内容！'); return; }

                    $lv.actionJson('/Msg/AddMsg', function (r) {
                        if (!r) return;
                        if (r.IsSuccess) {
                            dialog.closeBox();
                            $lv.toast('发送成功！');
                            ihub.sendNotice(noticeType.Msg, [toId]);
                        } else $lv.toast(r.Message);
                    }, null, { ReciveId: toId, Content: con });
                });
            });
        });
    }, attention: function (uid) {
        if (!this.checkLogin()) return;
        $lv.actionJson('/Home/Attention', function (r) {
            if (!r) return;
            $lv.toast(r.Message);
        }, null, { toId: uid, add: true });
    }, toBlack: function (uid, succeedCallback) {
        if (!this.checkLogin()) return;
        if (!confirm('确认拉黑吗？')) return;

        $lv.actionJson('/Home/ToBlack', function (r) {
            if (r && r.IsSuccess) {
                succeedCallback && succeedCallback();
                $lv.toast('已加入黑名单！');
            }
            else $lv.toast(r.Message);
        }, null, { toId: uid });
    },
    str2Json: function (jsonStr) {
        /// <summary>把Json字符串转为对象</summary>
        return JSON.parse(jsonStr);
    },

    json2Str: function (obj) {
        /// <summary>把对象转为Json字符串</summary>
        return JSON.stringify(obj);
    },
    downloadLaydateJs: function (callback) {
        $utl.downloadScript($siteUrl + 'Content/Plugs/laydate/laydate.js', 'laydate_src', callback);
    },
    lazyLaydateJs: function (callback) {
        $utl.lazyScript($siteUrl + 'Content/Plugs/laydate/laydate.js', 'laydate_src', callback);
    },
    downloadLocationxJs: function () {
        $utl.downloadScript($siteUrl + 'Content/Plugs/location/locationx.js', 'location_src');
    },
    lazyLocationxJs: function () {
        $utl.lazyScript($siteUrl + 'Content/Plugs/location/locationx.js', 'location_src');
    },
    downloadVchkJs: function () {
        $utl.downloadScript($siteUrl + 'Content/Scripts/vchk.js', 'vchk_src', function () { vchk.bindvchk(); });
    },
    lazyPoshytipJs: function (callback) {
        $utl.lazyScript($siteUrl + 'Content/Plugs/poshytip/jquery.poshytip.min.js', 'poshytip_src', callback);
    },
    lazyAliceJs: function (callback) {
        $utl.lazyScript($siteUrl + 'Content/Plugs/alice/alice.min.js', 'alice_src', callback);
    }
}